package com.ruike.alisurface.utils;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;

public abstract class CountTimeUtils {

    private long mMillisInFuture;
    private long mStopTimeInFuture;
    private boolean mCancelled = false;

    public CountTimeUtils(long secondInFuture) {
        this.mMillisInFuture = secondInFuture;
    }

    public synchronized final CountTimeUtils start() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = (SystemClock.elapsedRealtime() / 1000) + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }

    public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);

    }

    public abstract void onTick(long mMillisUntilFinished);

    public abstract void onFinish();

    private static final int MSG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(  Message msg) {
            super.handleMessage(msg);
            synchronized (CountTimeUtils.class) {
                if (mCancelled) {
                    return;
                }

                final long millisLeft = mStopTimeInFuture - (SystemClock.elapsedRealtime() / 1000);

                if (millisLeft <= 0) {
                    onFinish();
                } else {
                    onTick(millisLeft);
                    sendMessageDelayed(obtainMessage(MSG), 1000);
                }

            }
        }
    };
}
